# -*- coding: utf-8 -*-
# @Time :
# @Author : RLH
# @File :
# 功能描述: 接口注册中心
import io
from math import log
import os
from core.logging_utils_module import logs
from flask import request
from core.Base_Tools_modlue import BaseTools_Cls
from core.yaml_utils_module import YamlUtilsCls
from core.Operation_DB.SqlLite_DB import sqliteDatabase
from datetime import datetime
import json


API_resgister_conf_path = BaseTools_Cls.BasePathTrans_func(r'Module_Blueprint\regist_centre\conf\API_resgister_conf.yaml')


class FileService_cls:
    # 接收文件
    def allowed_file(self, filename):
        '''定义文件类型，返回Ture/Flase'''
        ALLOWED_EXTENSIONS = {'txt'}
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

    # 保存文件
    def save_file(self, file, filepath, filename):
        '''
        文件服务器中，保存文件上传的对象
        :param file:  文件对象
        :param filepath:  文件保存路劲
        :param filename:  文件名
        :return:
        '''
        if file and self.allowed_file(file.filename):
            file.save(os.path.join(filepath, filename))
            return True
        return False

    # 将数据写入文件
    def write_file(self, filedata, filepath, filename):
        if filedata:
            try:
                with io.open(os.path.join(filepath, filename), 'wt+',  encoding='utf-8') as f:
                    f.write(filedata)
            except Exception as e:
                return '文件写入失败:{}'.format(e)
        else:
            raise ValueError('响应报文不能为空')


    def read_file(self, filepath, filename):
        try:
            with io.open(os.path.join(filepath, filename), 'r',  encoding='utf-8') as f:
                data = f.read()
                return data
        except Exception as e:
            return '文件读取失败{}'.format(e)



    # 删除文件
    def delete_file(self, filepath, filename):
        file = os.path.join(filepath, filename)
        if os.path.isfile(file):
            os.remove(file)

    pass

class ApiConfigHandle_cls():

    # 写入API数据
    def add_api_data(self):
        db = sqliteDatabase()
        try:
            # 将API信息写入数据库
            id = db.get_uuid()
            api_name = request.form.get('api_name')
            url_path = request.form.get('url')
            template = request.form.get('api_name') + '.json'
            description = request.form.get('description')
            time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 获取当前时间并格式化
            if not url_path.startswith("/"):
                url_path = '/' + url_path

            sql = "INSERT INTO api_data (id,api_name,url_path,template,description, time) VALUES (?,?,?,?,?,?);"
            value = (id, api_name, url_path, template, description, time)
            db.insert_SQL(sql, value)
            db.close()

            # 将data中的数据写入文件
            filename = template
            filedata = request.form.get('data')
            # filedata = json.dumps(request.form.get('data'))
        
            # 从配置文件中获取到Api_module模块下template的路径配置
            filepath = BaseTools_Cls.BasePathTrans_func(
                YamlUtilsCls.read_yaml_func(API_resgister_conf_path)['Api_template_file_path']
            )

            FileService_cls().write_file(filename=filename, filepath=filepath, filedata=filedata)
            return '接口注册成功!!!'
        except Exception as e:
            logs.log('error', '接口注册失败')(e)
            return '接口注册失败'



    # 修改API数据
    def update_api_data(self):
        api_name = request.form.get('api_name')
        self.del_api_data(api_name)
        self.add_api_data()
        return "修改成功"


     # 删除API数据
    # @classmethod
    def del_api_data(self, api_name):
        db = sqliteDatabase()
        sql = 'select * from api_data where api_name = ?'
        value = (api_name,)
        api_data = list(db.select_SQL(sql, value)[0])
        if api_data:
            sql = 'delete  from api_data where api_name = ?'
            value = (api_name,)
            db.delete_SQL(sql, value)
            # 删除文件
            filename = api_name+'.json'
            # 从配置文件中获取到Api_module模块下template的路径配置
            filepath = BaseTools_Cls.BasePathTrans_func(
                YamlUtilsCls.read_yaml_func(API_resgister_conf_path)['Api_template_file_path']
            )

            FileService_cls().delete_file(filename=filename, filepath=filepath)
            return True
        db.close()
        return False

    # 后端接口--展示api数据
    # @classmethod
    def dis_api_data(self, api_name):
        db = sqliteDatabase()
        try:
            sql = 'select * from api_data where api_name = ?'
            value = (api_name,)
            api_data = list(db.select_SQL(sql, value)[0])
            filename = api_name + '.json'
            # 从配置文件中获取到Api_module模块下template的路径配置
            filepath = BaseTools_Cls.BasePathTrans_func(
                YamlUtilsCls.read_yaml_func(API_resgister_conf_path)['Api_template_file_path']
            )

            # data = json.loads(FileService_cls().read_file(filename=filename, filepath=filepath))
            data = FileService_cls().read_file(filename=filename, filepath=filepath)
        except Exception as e:
            return e
        db.close()
        return api_data, data

    def read_apidata_all(self):
        """
        函数作用：查询api_data表中的所有api_name和description列，并返回列表
        """
        db = sqliteDatabase()
        sql = "select api_name, description  from api_data order by time desc"
        api_data = db.select_SQL(SQL_template=sql)
        db.close()
        return api_data


ApiConfigHandle_cls = ApiConfigHandle_cls()

if __name__ == '__main__':
    print(ApiConfigHandle_cls.dis_api_data('test2'))



